import {AfterViewInit, Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {e} from '@angular/core/src/render3';
declare var tinymce: any;
@Component({
  selector: 'app-tiny-editor',
  templateUrl: './tiny-editor.component.html',
  styleUrls: ['./tiny-editor.component.css']
})

export class TinyEditorComponent implements AfterViewInit, OnDestroy {
  @Input() elementId: String;
  @Output() onEditorContentChange = new EventEmitter();

  editor;

  constructor(private http: HttpClient) { }

  ngAfterViewInit() {
    const self = this;
    tinymce.init({
      selector: '#' + this.elementId,
      height: 600,
      plugins: ['link', 'table', 'image'],
      skin_url: 'assets/skins/lightgray',
      setup: editor => {
        this.editor = editor;
        editor.on('keyup change', () => {
          const content = editor.getContent();
          this.onEditorContentChange.emit(content);
        });
      },
      // 图片上传功能
      images_upload_handler: function(blobInfo, success, failure) {
        let formData;
        formData = new FormData();
        console.log(blobInfo);
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        console.log(formData);
        self.uploadFile('http://wl.cs/admin/upload/upload', formData).subscribe( response => {
          console.log('图片上传结果')
          console.log(response)
          if (response && response['data'] && response['data']['path']) {
            const url = response['data']['path'];
            // 把图片链接，img src标签显示图片的有效链接放到下面回调函数里
            success(url);
          } else {
            if (response && response['msg']) {
              failure(response['msg']);
            } else {
              failure('上传失败：未知错误');
            }
          }
        });
      }
    });
  }

  // 上传图片
  private uploadFile(url: string, formData: any) {
    const self = this;
    const headers = new HttpHeaders();
    headers.set('Accept', 'application/json');
    return self.http.post(url, formData, { headers: headers });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }

}
